#include "FileVersion.h"
#include <windows.h>

bool FileVersion::GetVersion(std::wstring fileName, VersionInfo& out)
{
    bool bSuc = false;
    LPBYTE lpData = NULL;
    DWORD dwHandle = 0;
    DWORD dwLen = GetFileVersionInfoSize(fileName.c_str(), &dwHandle);
    if (dwLen == 0)
    {
        printf("获取文件版本信息大小失败。\n");
        goto done;
    }

    lpData = new BYTE[dwLen];
    if (!GetFileVersionInfo(fileName.c_str(), dwHandle, dwLen, lpData))
    {
        printf("获取文件版本信息失败。\n");
        goto done;
    }

    VS_FIXEDFILEINFO* pFileInfo = nullptr;
    UINT uiLen;
    
    if (VerQueryValue(lpData, _T("\\"), (LPVOID*)&pFileInfo, &uiLen))
    {        
        out.Major = HIWORD(pFileInfo->dwFileVersionMS);
        out.Minor = LOWORD(pFileInfo->dwFileVersionMS);
        out.Build = HIWORD(pFileInfo->dwFileVersionLS);
        out.Revision = LOWORD(pFileInfo->dwFileVersionLS);

        bSuc = true;
    }    

done:

    if(lpData)
        delete[] lpData;

    return bSuc;
}
